package com.hmdp.service.impl;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.CaCheClient;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.RedisData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    @Resource
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    CaCheClient caCheClient;


    @Override
    public Result queryById(Long id) {
        Shop shop = caCheClient.queryWithPassThrough(CACHE_SHOP_KEY, id, Shop.class, this::getById, CACHE_SHOP_TTL, TimeUnit.MINUTES);
        if (shop == null) {
            return Result.fail("店铺不存在！");
        }
        return Result.ok(shop);
    }

    //声明一个线程池
    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);

    /*基于逻辑过期解决缓存击穿*/
    private Shop queryWithLogicExpire(Long id) {
        String key = CACHE_SHOP_KEY + id;
        String shopJson = stringRedisTemplate.opsForValue().get(key);
        //未命中redis，直接返回空
        if (StrUtil.isBlank(shopJson)) {
            return null;
        }
        RedisData redisData = JSONUtil.toBean(shopJson, RedisData.class);
        Shop shop = JSONUtil.toBean((JSONObject) redisData.getData(), Shop.class);
        //命中
        //判断缓存是否过期
        //未过期，返回商铺信息
        if (redisData.getExpireTime().isAfter(LocalDateTime.now())) {
            return shop;
        }
        try {
            //过期，尝试获取互斥锁
            if (tryBlock(key)) {
                //获取到了，开始独立线程
                CACHE_REBUILD_EXECUTOR.submit(() -> {
                    this.saveShop2Redis(id, 20L);
                });
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            //释放锁
            delBlock(key);
        }
        //没有获取到，返回过期的店铺信息
        return shop;
    }


    /*缓存击穿*/
    public Shop queryWithMutex(Long id) {
        /*先从redis里面查缓存*/
        String key = RedisConstants.CACHE_SHOP_KEY + id;//定义一个key
        String shopJson = stringRedisTemplate.opsForValue().get(key);//得到json格式的数据
        if (StrUtil.isNotBlank(shopJson)) {
            /*如果有，直接返回*/
            return JSONUtil.toBean(shopJson, Shop.class);
        }

        if (shopJson != null) {
            //命中到空值了
            return null;
        }
        //获取锁
        String keyLock = LOCK_SHOP_KEY + id;
        Shop shop = null;
        try {
            boolean isLock = tryBlock(keyLock);
            if (!isLock) {
                //获取锁失败
                //睡眠
                Thread.sleep(50);
                //再重新去请求
                return queryWithMutex(id);
            }
            /*如果redis里面没有数据，走数据库查*/
            shop = getById(id);
            if (shop == null) {
                /*从数据库查看是否有相应的数据*/
                /*没有，给redis中缓存空字符串并返回错误信息*/
                stringRedisTemplate.opsForValue().set(key, "", RedisConstants.CACHE_NULL_TTL, TimeUnit.MINUTES);
                return null;
            }
            /*有，先写进redis*/
            stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(shop), RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);//实体类转json格式
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            //释放锁
            delBlock(keyLock);
        }
        /*返回数据*/
        return shop;
    }


    /*缓存穿透*/
    public Shop queryWithPassThrough(Long id) {
        /*先从redis里面查缓存*/
        String key = RedisConstants.CACHE_SHOP_KEY + id;//定义一个key
        String shopJson = stringRedisTemplate.opsForValue().get(key);//得到json格式的数据
        if (StrUtil.isNotBlank(shopJson)) {
            /*如果有，直接返回*/
            return JSONUtil.toBean(shopJson, Shop.class);
        }

        if (shopJson != null) {
            //命中到空值了
            return null;
        }
        /*如果redis里面没有数据，走数据库查*/
        Shop shop = getById(id);
        if (shop == null) {
            /*从数据库查看是否有相应的数据*/
            /*没有，给redis中缓存空字符串并返回错误信息*/
            stringRedisTemplate.opsForValue().set(key, "", RedisConstants.CACHE_NULL_TTL, TimeUnit.MINUTES);
            return null;
        }
        /*有，先写进redis*/
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(shop), RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);//实体类转json格式
        /*返回数据*/
        return shop;
    }

    /*获取锁*/
    private boolean tryBlock(String key) {
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(flag);
    }

    /*释放锁*/
    private void delBlock(String key) {
        stringRedisTemplate.delete(key);
    }

    /*热点key预热*/
    public void saveShop2Redis(Long id, Long expireSeconds) {

        //查店铺
        Result shop = queryById(id);
        RedisData redisData = new RedisData();
        redisData.setData(shop);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(expireSeconds));
        //写入redis
        stringRedisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_KEY + id, JSONUtil.toJsonStr(redisData));
    }

    @Override
    @Transactional
    public Result update(Shop shop) {
        /*数据一致性问题*/
        if (shop.getId() == null) {
            return Result.fail("店铺id不能为空");
        }
        /*先更新数据库*/
        updateById(shop);
        /*后删除redis缓存*/
        stringRedisTemplate.delete(RedisConstants.CACHE_SHOP_KEY + shop.getId());
        return Result.ok();
    }
}
